/*
* 直接更新 state 的多个方法的对象
* */
import {
  RECEIVE_INDEX,
  RECEIVE_GOOGS,
  RECEIVE_CATEGORIES,
  RECEIVE_USER_INFO,
  RESET_USER_INFO,
  Add_CARTGOODS,
  RECEIVE_GOODSLIST,
  UPDATE_CARTGOODS,
  REMOVE_CARTGOODS,
  REMOVE_GOODSLIST,
  UPDATE_CARTGOODS_SELECTED
} from "./mutation-types"

export default {
  [RECEIVE_INDEX] (state, {index}) {
    state.index = index
  },
  [RECEIVE_GOOGS] (state, {goods}) {
    state.goods = goods
  },
  [RECEIVE_CATEGORIES] (state, {categories}) {
    state.categories = categories
  },
  [RECEIVE_USER_INFO] (state, {userInfo}) {
    state.userInfo = userInfo
  },
  [RESET_USER_INFO] (state) {
    state.userInfo = {}
  },
  [Add_CARTGOODS] (state, {goodsInfo}) {
    // 1. 如果购物车中, 之前就有这个对应的商品, 那么, 只需要更新数量
    // 2. 如果没有, 则直接商品数据 push 到 carts 中
    // 在购物车中是否找到对应商品的标识
    let flag = false
    state.cartGoods.some(item =>　{
      if (item.id === goodsInfo.id) {
        item.count += parseInt(goodsInfo.count)
        flag = true
        return true
      }
    })

    // 如果最终循环完毕, flag 还是 false, 则把商品数据直接 push 到购物车中
    if (!flag) {
      state.cartGoods.push(goodsInfo)
    }

    // 更新完 cartGoods 之后, 把数组存到 本地存储中
    localStorage.setItem('cartGoods', JSON.stringify(state.cartGoods))
  },
  [RECEIVE_GOODSLIST] (state, {goodsList}) {
    state.goodsList = goodsList
    // console.log(state.goodsList, '--------receive_goodslist')
  },
  [UPDATE_CARTGOODS] (state, {goodsInfo}) {
    // 修改购物轧商品的数量值
    state.cartGoods.some(item => {
      if (item.id === goodsInfo.id) {
        item.count = parseInt(goodsInfo.count)
        return true
      }
    })
    // 当修改完商品的数量, 在本地存储中更新之前的数据
    localStorage.setItem('cartGoods', JSON.stringify(state.cartGoods))
  },
  [REMOVE_CARTGOODS] (state, {id}) {
    let cartGoods = state.cartGoods.some((item, i) => {
      if (item.id === id) {
        state.cartGoods.splice(i, 1)
        return true
      }
    })
    // 将删除完毕后的, 最新的购物车数据, 同步到 本地存储中
    localStorage.setItem('cartGoods', JSON.stringify(state.cartGoods))
  },
  [REMOVE_GOODSLIST] (state, {index}) {
    state.goodsList.splice(index, 1)
  },
  [UPDATE_CARTGOODS_SELECTED] (state, {id, val}) {
    state.cartGoods.some(item => {
      if (item.id === id) {
        item.selected = val
      }
    })
    // 把最新的 所有购物车商品的状态更新到s tore 中
    localStorage.setItem('cartGoods', JSON.stringify(state.cartGoods))
  }
}
